package com.me.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.me.bean.Xy;
import com.me.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XyDao extends BaseDao {

    String TABLE_NAME = "xy";

    /**
     * delete by uid(doc's id), not record id
     */
    public void delete(final long id) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = null;
                try {
                    db = getDataBase();
                    int result = db.delete(TABLE_NAME, "id=?", new String[]{String.valueOf(id)});
                    System.currentTimeMillis();
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    if (db != null) {
                        closeDataBase();
                    }
                }
            }
        });
    }

    public void insert(Xy bean, DBListener listener) {
        doInBackground(new Runnable() {

            @Override
            public void run() {
                SQLiteDatabase db = null;
                try {
                    db = getDataBase();
                    if (db == null) {
                        if (listener != null) {
                            listener.onResult(false, "", null);
                        }
                        return;
                    }
                    ContentValues values = new ContentValues();
                    values.put("xyh", bean.high);
                    values.put("xyl", bean.low);
                    values.put("time", bean.time);
                    long id = db.insert(TABLE_NAME, null, values);
                    if (listener != null) {
                        listener.onResult(id != -1, null, id);
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    if (db != null) {
                        closeDataBase();
                    }
                }
            }
        });
    }

    public void getAll(DBListener listener) {
        doInBackground(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase db = null;
                Cursor cursor = null;
                try {
                    db = getDataBase();
                    if (db == null) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyMap());
                        }
                        return;
                    }
                    cursor = db.rawQuery("select * from " + TABLE_NAME + " order by time desc", null);
                    if (cursor == null || cursor.getCount() <= 0) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyMap());
                        }
                        return;
                    }
                    List<String> date = new ArrayList<>();
                    List<List<Xy>> list = new ArrayList<>();
                    while (cursor.moveToNext()) {
                        Xy item = new Xy();
                        item.high = cursor.getInt(cursor.getColumnIndexOrThrow("xyh"));
                        item.time = cursor.getLong(cursor.getColumnIndexOrThrow("time"));
                        item.id = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
                        item.low = cursor.getInt(cursor.getColumnIndexOrThrow("xyl"));
                        String day = Utils.getDay(item.time);
                        if (date.contains(day)) {
                            list.get(list.size() - 1).add(item);
                        } else {
                            date.add(day);
                            List<Xy> tmp = new ArrayList<>();
                            tmp.add(item);
                            list.add(tmp);
                        }
                    }
                    Map map = new HashMap();
                    map.put("day", date);
                    map.put("data", list);
                    if (listener != null) {
                        listener.onResult(true, null, map);
                    }
                } catch (Throwable e) {
                    if (listener != null) {
                        listener.onResult(false, e.toString(), Collections.emptyList());
                    }
                } finally {
                    closeCursor(cursor);
                    if (db != null) {
                        closeDataBase();
                    }
                }
            }
        });
    }

    public void getOneDay(String oneDay, DBListener listener) {
        doInBackground(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase db = null;
                Cursor cursor = null;
                try {
                    db = getDataBase();
                    if (db == null) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyList());
                        }
                        return;
                    }
                    cursor = db.rawQuery("select * from " + TABLE_NAME + " order by time desc", null);
                    if (cursor == null || cursor.getCount() <= 0) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyList());
                        }
                        return;
                    }
                    long time = date2Ms(oneDay);
                    List<Xy> list = new ArrayList<>();
                    while (cursor.moveToNext()) {
                        Xy item = new Xy();
                        item.high = cursor.getInt(cursor.getColumnIndexOrThrow("xyh"));
                        item.time = cursor.getLong(cursor.getColumnIndexOrThrow("time"));
                        item.id = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
                        item.low = cursor.getInt(cursor.getColumnIndexOrThrow("xyl"));
                        String day = Utils.getDay(item.time);
                        if (day.equals(oneDay)) {
                            list.add(item);
                        } else if (item.time < time) {
                            break;
                        }
                    }
                    if (listener != null) {
                        listener.onResult(true, null, list);
                    }
                } catch (Throwable e) {
                    if (listener != null) {
                        listener.onResult(false, e.toString(), Collections.emptyList());
                    }
                } finally {
                    closeCursor(cursor);
                    if (db != null) {
                        closeDataBase();
                    }
                }
            }
        });
    }

    public void getWeek(String oneDay, DBListener listener) {
        long time = date2Ms(oneDay);
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);

        Calendar tmp = Calendar.getInstance();
        tmp.set(Calendar.YEAR, c.get(Calendar.YEAR));
        tmp.set(Calendar.MONTH, c.get(Calendar.MONTH));
        tmp.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
        tmp.set(Calendar.HOUR_OF_DAY, 0);
        tmp.set(Calendar.MINUTE, 0);
        tmp.set(Calendar.SECOND, 0);

        Calendar tmp2 = Calendar.getInstance();
        tmp2.set(Calendar.YEAR, c.get(Calendar.YEAR));
        tmp2.set(Calendar.MONTH, c.get(Calendar.MONTH));
        tmp2.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
        tmp2.set(Calendar.HOUR_OF_DAY, 23);
        tmp2.set(Calendar.MINUTE, 59);
        tmp2.set(Calendar.SECOND, 59);

        int i = c.get(Calendar.DAY_OF_WEEK);
        long start;
        if (i > 1) {
            tmp.add(Calendar.DAY_OF_MONTH, -(i - 1));
        }
        start = tmp.getTimeInMillis();
        long end;
        if (i < 7) {
            tmp2.add(Calendar.DAY_OF_MONTH, (7 - 1));
        }
        end = tmp2.getTimeInMillis();
        doInBackground(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase db = null;
                Cursor cursor = null;
                try {
                    db = getDataBase();
                    if (db == null) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyList());
                        }
                        return;
                    }
                    cursor = db.rawQuery("select * from " + TABLE_NAME + " order by time desc", null);
                    if (cursor == null || cursor.getCount() <= 0) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyList());
                        }
                        return;
                    }
                    List<Xy> list = new ArrayList<>();
                    while (cursor.moveToNext()) {
                        Xy item = new Xy();
                        item.high = cursor.getInt(cursor.getColumnIndexOrThrow("xyh"));
                        item.time = cursor.getLong(cursor.getColumnIndexOrThrow("time"));
                        item.id = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
                        item.low = cursor.getInt(cursor.getColumnIndexOrThrow("xyl"));
                        if (item.time > end) {
                            continue;
                        }
                        if (item.time < start) {
                            break;
                        }
                        list.add(item);
                    }
                    if (listener != null) {
                        listener.onResult(true, null, list);
                    }
                } catch (Throwable e) {
                    if (listener != null) {
                        listener.onResult(false, e.toString(), Collections.emptyList());
                    }
                } finally {
                    closeCursor(cursor);
                    if (db != null) {
                        closeDataBase();
                    }
                }
            }
        });
    }

    public void getMonth(String oneDay, DBListener listener) {
        long time = date2Ms(oneDay);
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);

        Calendar tmp = Calendar.getInstance();
        tmp.set(Calendar.YEAR, c.get(Calendar.YEAR));
        tmp.set(Calendar.MONTH, c.get(Calendar.MONTH));
        tmp.set(Calendar.DAY_OF_MONTH, 1);
        tmp.set(Calendar.HOUR_OF_DAY, 0);
        tmp.set(Calendar.MINUTE, 0);
        tmp.set(Calendar.SECOND, 0);

        Calendar tmp2 = Calendar.getInstance();
        tmp2.set(Calendar.YEAR, c.get(Calendar.YEAR));
        tmp2.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);
        tmp2.set(Calendar.DAY_OF_MONTH, 1);
        tmp2.set(Calendar.HOUR_OF_DAY, 23);
        tmp2.set(Calendar.MINUTE, 59);
        tmp2.set(Calendar.SECOND, 59);
        tmp2.add(Calendar.DAY_OF_MONTH, -1);

        long start = tmp.getTimeInMillis();
        long end = tmp2.getTimeInMillis();
        doInBackground(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase db = null;
                Cursor cursor = null;
                try {
                    db = getDataBase();
                    if (db == null) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyList());
                        }
                        return;
                    }
                    cursor = db.rawQuery("select * from " + TABLE_NAME + " order by time desc", null);
                    if (cursor == null || cursor.getCount() <= 0) {
                        if (listener != null) {
                            listener.onResult(false, "", Collections.emptyList());
                        }
                        return;
                    }
                    List<Xy> list = new ArrayList<>();
                    while (cursor.moveToNext()) {
                        Xy item = new Xy();
                        item.high = cursor.getInt(cursor.getColumnIndexOrThrow("xyh"));
                        item.time = cursor.getLong(cursor.getColumnIndexOrThrow("time"));
                        item.id = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
                        item.low = cursor.getInt(cursor.getColumnIndexOrThrow("xyl"));
                        if (item.time > end) {
                            continue;
                        }
                        if (item.time < start) {
                            break;
                        }
                        list.add(item);
                    }
                    if (listener != null) {
                        listener.onResult(true, null, list);
                    }
                } catch (Throwable e) {
                    if (listener != null) {
                        listener.onResult(false, e.toString(), Collections.emptyList());
                    }
                } finally {
                    closeCursor(cursor);
                    if (db != null) {
                        closeDataBase();
                    }
                }
            }
        });
    }

    private long date2Ms(String _data) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        try {
            Date date = format.parse(_data);
            return date.getTime();
        } catch (Exception e) {
            return 0;
        }
    }

    public void getLast(DBListener listener) {
        doInBackground(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase db = null;
                Cursor cursor = null;
                try {
                    db = getDataBase();
                    if (db == null) {
                        if (listener != null) {
                            listener.onResult(false, "", null);
                        }
                        return;
                    }
                    cursor = db.rawQuery("select * from " + TABLE_NAME + " order by time desc", null);
                    if (cursor == null || cursor.getCount() <= 0) {
                        if (listener != null) {
                            listener.onResult(false, "", null);
                        }
                        return;
                    }
                    while (cursor.moveToNext()) {
                        Xy item = new Xy();
                        item.high = cursor.getInt(cursor.getColumnIndexOrThrow("xyh"));
                        item.time = cursor.getLong(cursor.getColumnIndexOrThrow("time"));
                        item.id = cursor.getLong(cursor.getColumnIndexOrThrow("id"));
                        item.low = cursor.getInt(cursor.getColumnIndexOrThrow("xyl"));
                        if (listener != null) {
                            listener.onResult(true, null, item);
                        }
                        return;
                    }
                } catch (Throwable e) {
                    if (listener != null) {
                        listener.onResult(false, e.toString(), Collections.emptyList());
                    }
                } finally {
                    closeCursor(cursor);
                    if (db != null) {
                        closeDataBase();
                    }
                }
            }
        });
    }
}
